/**
 * This file is part of the dspace-poltman project http://www.poltman.com.
 *
 * This is free software; you can redistribute it and/or modify it under
 * the terms of DuraSpace DSpace license detailed in the LICENSE and NOTICE 
 * files at the root of the source tree and available online at
 * http://www.dspace.org/license/
 * 
 */
package com.poltman.dscentral.security;

import java.io.Serializable;

import org.apache.log4j.Logger;
import org.dspace.core.Context;
import org.dspace.eperson.EPerson;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Page;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.metainfo.ComponentInfo;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zkplus.spring.SpringUtil;
import org.zkoss.zul.Messagebox;


/**
 * 
 * @author zciok
 * @version $Revision: 1775 $
 */
public class ZulSecurityController extends SelectorComposer<Component> implements Serializable {

	private static final long serialVersionUID = 8045028912235851574L;
	
	private static Logger log = Logger.getLogger(ZulSecurityController.class);

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public ComponentInfo doBeforeCompose(Page page, Component parent, ComponentInfo compInfo)  {	
    	try {
    		String requestPath = Executions.getCurrent().getDesktop().getRequestPath();
    		
    		if ("/pages/login/login.zul".equals(requestPath)) return super.doBeforeCompose(page, parent, compInfo);
    		if ("/pages/register/registration-form.zul".equals(requestPath)) return super.doBeforeCompose(page, parent, compInfo);
    		
    		Context context = (Context)SpringUtil.getBean("context");
    		EPerson eperson = context.getCurrentUser();
    		if (eperson == null) {
    			String remoteAddr = Executions.getCurrent().getRemoteAddr();
    			log.warn("Illegal attempt to open " + page.getId() + " by " + remoteAddr);
    			
    			context.clear();
    			
    			Messagebox.show("Illegal attempt to open", "DSCentral", Messagebox.OK, Messagebox.QUESTION, new org.zkoss.zk.ui.event.EventListener() {
    			    public void onEvent(Event evt) throws InterruptedException {
    			    	Executions.sendRedirect("/index.jsp");
    			    }
    			});    			
    			return null;
    		} else {
    			log.info(page.getId() + " opened by " + context.getCurrentUser().getEmail());
    		}
    	} catch (Exception e) {
    		log.error("ZulSecurityController ", e);
    		return null;
    	}
    	return super.doBeforeCompose(page, parent, compInfo);
	}
}
